<?php
namespace Todo\Model\Base;

use Todo\Model\BaseModel;
use Todo\Service\DictService;

class ClassModel extends BaseModel
{
    public $tableName = 'base_class';

    public $_validate = array(
        array('title', 'require', '请输入班级名称'),
        array('title','1,50','名称长度超出限制！',1,'length'),
        array('grade', 'require', '请输入班级年级'),
        array('system', 'require', '请输入班级学制')
    );

    protected $_auto = array(
        array('master_user', '_master', self::MODEL_BOTH, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    protected function _master(){
        $master = I('post.master');
        if(!$master) return 0;
        
        return D('Todo/Base/Teacher')->findOne(array('tnt_id'=>TNT_ID,'number'=>$master), 'user_id');
    }

    /**
     * 导入一行数据
     * @param $row 数据
     * @param int $exists=1 数据冲突处理方式：1报错，2跳过，3覆盖
     * @return bool
     */
    public function importOne($row, $exists=1){
        if(count($row) < 4 || !$row[0] || !$row[1]  || !$row[2]  || !$row[3]){
            $this->error = "班级名称、专业、年级、学制不能为空";
            return false;
        }
        $data = array(
            'title' => $row[0],
            'grade' => $row[2],
            'system' => $row[3],
        );
        $data['depart_id'] = D('Todo/Base/Department')->where(array('title'=>$row[1]))->cache(true)->getField('id');

        if(count($row)>4 && $row[4]) {// 状态
            $data['status'] = DictService::getInstance()->getDictValue('STATUS', $row[4]);
        }else{
            $data['status'] = '1';
        }

        if(count($row)>5 && $row[5]) {//班主任负责人
            $info = D('Todo/Base/Teacher')->findOne(array('tnt_id'=>TNT_ID,'number'=> $row[5]));
            if(!$info || $info['name'] != $row[6]){
                $this->error = '班主任('.$row[5].':'.$row[6].')不存在';
                return false;
            }
            $data['master_user'] = $info['user_id'];
        }else{
            $data['master_user'] = 0;
        }
        $old = $this->where(array('title' => $row[0]))->find();
        if($old){ //班级名称已存在
            if($exists == 1) {
                $this->error = '名称为（'.$row[0].'）的班级信息已经存在';
                return false;
            }else if($exists == 2) return true;
            else{
                $old = array_merge($old, $data);
                return $this->save($old) !== false;
            }
        }else{ //班级不存在
            return $this->add($data);
        }
    }
}